import { defineStore } from "pinia"
import { useApiStore } from "@/app/api/apiStore"
import { IUserInfo, UserType } from "@/app/api/api"
import { computed, ref } from "vue"
import { timestampMS } from "@/utils/timeUtils/timestamp"
import { persistKey } from "../persistKey"


const storeKey = 'userInfo'
export const useUserInfoStore = defineStore(storeKey, ()=>{
    const userInfo = ref<IUserInfo>()
    const userInfoFetchedAtMS = ref<number>()
    const isAdmin = computed<boolean>(()=>{
        return (userInfo.value?.type ?? 0) >=UserType.Admin
    })
    const apiStore = useApiStore()

    /**
     * 获取身份信息（确保最新（检查缓存是否过期））
     * @param enforceNew 强制从服务器获取，不读缓存
     */
    async function getIdentityInfo(enforceNew?:boolean):Promise<IUserInfo|undefined> {
        let res:IUserInfo|undefined = undefined
        if(!enforceNew){
            if(valueReadable())
                res = userInfo.value
        }
        if(!res){
            res = await apiStore.auth.info()
            if (res) {
                log("获取服务器响应:", res)
            }
            userInfoFetchedAtMS.value = timestampMS()
        }
        else{
            log("获取缓存:",res)
        }
        userInfo.value = res
        return res;
    }

    function clearValue(){
        userInfo.value = undefined;
        userInfoFetchedAtMS.value = 0;
        log("清除缓存")
    }
    function valueReadable():boolean{
        const stored = userInfo.value
        if(stored){
            const fetchedAt = userInfoFetchedAtMS.value || 0
            const now = timestampMS()
            if(now - fetchedAt < identityCacheExpireMs){
                //缓存有效
                return true
            }
        }
        return false
    }

    return { 
        userInfo,
        userInfoFetchedAtMS,
        isAdmin,
        getIdentityInfo,
        clearValue
    }
}, {
    persist:{
        key: persistKey(storeKey),
        pick:['userInfo', 'userInfoFetchedAtMS']
    }
})


const logPrefix = "[身份信息]"
const log = (msg:string, ...data:any[])=>console.log(`${logPrefix}${msg}`, ...data)
const identityCacheExpireSec = 60 //一分钟内刷新不再重复获取，直接读取缓存
const identityCacheExpireMs = identityCacheExpireSec * 1000